﻿using System;
using System.Windows.Forms;
using AutoUpdaterDotNET;

namespace Publisher
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();
            
            
            // Configure AutoUpdater.NET
            AutoUpdater.Start("http://192.168.31.102:9100/frontend/autoUpdater/update.xml");

            // Optional: Customize AutoUpdater behavior
            AutoUpdater.Mandatory = true; // Force updates if needed
            AutoUpdater.UpdateMode = Mode.Normal; // Options: Normal, Forced, ForcedDownload
            AutoUpdater.RunUpdateAsAdmin = false; // False by default

            
            AutoUpdater.CheckForUpdateEvent += AutoUpdaterOnCheckForUpdateEvent  ;
        }

        private void AutoUpdaterOnCheckForUpdateEvent(UpdateInfoEventArgs args)
        {
           
            if (args == null)
            {
                MessageBox.Show("There was a problem reaching the update server. Please try again later.", 
                    "Update Check Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (args.IsUpdateAvailable)
            {
                // Notify the user about the update
                var dialogResult = MessageBox.Show(
                    $"A new version ({args.CurrentVersion}) is available! You are currently using version {args.InstalledVersion}.\n\n" +
                    "Do you want to update now?",
                    "Update Available",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Information);

                if (dialogResult == System.Windows.Forms.DialogResult.Yes )
                {
                    try
                    {
                        // Start the update process
                        AutoUpdater.DownloadUpdate(args);

                        Environment.Exit(0);

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"Update failed: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            else
            {
                // Inform the user that the app is up-to-date
                // MessageBox.Show("You are already using the latest version.", 
                    // "No Update Available", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    
            }
        
        
            
        }
    }
}